package rocky.freemanagementsystemserver.controller

import org.apache.commons.lang3.StringUtils
import org.apache.shiro.SecurityUtils
import org.apache.shiro.authc.AuthenticationException
import org.apache.shiro.authc.UnknownAccountException
import org.apache.shiro.authc.UsernamePasswordToken
import org.apache.shiro.authz.AuthorizationException
import org.apache.shiro.subject.Subject
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import retrofit2.http.Body
import rocky.freemanagementsystemserver.Entity.User
import rocky.freemanagementsystemserver.bean.CommomResult
import rocky.freemanagementsystemserver.bean.CommonException
import rocky.freemanagementsystemserver.bean.ErrorCode
import rocky.freemanagementsystemserver.service.interfaces.IUserService
import rocky.freemanagementsystemserver.utils.Slf4j
import rocky.freemanagementsystemserver.utils.Slf4j.Companion.log
import javax.naming.AuthenticationException


@RestController
@RequestMapping("/token")
@Slf4j
class TokenController {

    @Autowired
    lateinit var userService: IUserService

    @PostMapping
    fun login(@RequestBody user: User): Boolean {
        if (StringUtils.isEmpty(user.name) || StringUtils.isEmpty(user.password)) {
            throw CommonException("请输入用户名和密码", ErrorCode.ParameterError);
        }
        //用户认证信息
        //用户认证信息
        val subject: Subject = SecurityUtils.getSubject()
        val usernamePasswordToken = UsernamePasswordToken(
            user.name,
            user.password
        )
        try {
            //进行验证，这里可以捕获异常，然后返回对应信息
            subject.login(usernamePasswordToken)
//            subject.checkRole("admin");
//            subject.checkPermissions("query", "add");
        } catch (e: UnknownAccountException) {
            log.error("用户名不存在！", e)
            throw Exception("用户名不存在！")
        } catch (e: AuthenticationException) {
            log.error("账号或密码错误！", e)
            throw Exception("账号或密码错误！")
        } catch (e: AuthorizationException) {
            log.error("没有权限！", e)
            throw Exception("没有权限")
        }
        return true
    }
}